require 'roled/models/aco'
namespace :acos do
	task :generate => :environment do
	  
	  if !ActiveRecord::Base.connection.table_exists? 'acos'
	    abort("Roled is not installed correctly...")
	  end
	  
	  routes = Rails.application.routes.routes.to_a
	  
	  
	  @actions = Roled::Aco.all
	  
	  if(@actions.blank?)
	    Roled::Aco.new(:parent => "all").save
	    puts "New install, preparing table..."
	  end
	 
	  routes.each do |route|
	    if !route.defaults.blank?
	      if !defined?(controller) || controller != route.defaults[:controller]
	        controller = route.defaults[:controller]
	        create_action(controller)
	      end
	      action = route.defaults[:action]
	      create_action(controller, action)
	    end
	  end
		
      dir = Rails.root.join('app', 'controllers').to_s
		
	  @controllers = Dir.entries(dir)
	  @actions = Roled::Aco.all
	  	
      @controllers.each do |name|
			if name=~ /^(?!application).*_controller.rb/
				controller = File.read(dir + '/' + name)
				name = name.gsub('_controller.rb', "")
				create_action(name)
				
				lines = controller.split(/\r?\n/)
				ignore = false
				lines.each do |l|
				  if l.strip =~ /(\Aprotected\z|\Aprivate\z)/ && !ignore
					ignore = true
				  elsif l.strip == "public" && ignore
				    ignore = false
				  elsif l.strip =~ /\Adef \w*/ && !ignore
				    create_action(name, l.gsub('def','').strip!)
				  end
				end
			end
		end
      puts "All done! :)"
	end	
end

def create_action(controller = nil, action = nil)
    controller_name = "#{controller}_controller"
	if(!Roled::Aco.where(:action => action, :parent => controller_name).exists?)
		if(action.blank?)
		  puts "Saving controller: #{controller} "
		else
		  puts "Saving action: #{controller}##{action} "
		end
		Roled::Aco.new(:action => action, :parent => controller_name).save
	end
	
end